package msu.ml.tools.birdminer;

import java.util.*;
import weka.core.*;
import msu.ml.core.*;
import msu.ml.data.*;
import msu.ml.data.level2.*;

public class DatabaseDataSource implements IDataSource
{
   private DatabaseModel model;
   private String [] names;
   private IPulseVolumeSQLAdapter adapter;

   public DatabaseDataSource(DatabaseModel model, IPulseVolumeSQLAdapter adapter)
   {
      this(model, adapter, 0, false);
   }

   public DatabaseDataSource(DatabaseModel model, IPulseVolumeSQLAdapter adapter, int limit, boolean rand)
   {
      this.model = model;
      this.adapter = adapter;
      List<String> list = model.getVolumeNames(limit, rand);
      this.names = list.toArray(new String[0]);
   }

   public int volumeCount()
   {
      return this.names.length;
   }

   public String [] getVolumeNames()
   {
      return this.names;
   }

   public NxInstances getSweepForVolume(String vname)
   {
      NxInstances instances = null;
      for(IPulseVolume pulse : model.getPulseVolumes(vname, adapter))
      {
         if(instances == null)
         {
            String [] attributes = pulse.getFeatureNames();
            FastVector v = new FastVector(attributes.length);
            for(int i = 0; i < attributes.length - 1; i++)
               v.addElement(new Attribute(attributes[i]));
            FastVector classes = new FastVector(2);
            classes.addElement("0");
            classes.addElement("1");
            v.addElement(new Attribute("class", classes));
            instances = new NxInstances(vname, v, 1024);
         }
         instances.add(new Instance(1.0, pulse.getFeatures()));
      }

      if(instances != null)
      {
         instances.setSourceFile(vname);
         instances.setClassIndex(instances.numAttributes() - 1);
      }
      return instances;
   }
}
